package com.itboye.ihomebank.activity.me;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.itboye.ihomebank.R;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.base.MyApplcation;
import com.itboye.ihomebank.bean.PersonDataBean;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.constants.NetPublicConstant;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.custom.RoundImageView;
import com.itboye.ihomebank.presenter.UserPresenter;
import com.itboye.ihomebank.util.uploadmultipleimage.MultipartRequest;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.CameraPopupWindow;
import com.itboye.ihomebank.util.GlideLoader;
import com.itboye.ihomebank.util.SPUtils;
import com.itboye.ihomebank.util.SavePersonData;
import com.itboye.ihomebank.util.XImageLoader;
import com.yancy.imageselector.ImageConfig;
import com.yancy.imageselector.ImageSelector;
import com.yancy.imageselector.ImageSelectorActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;

/**
 * 个人信息
 */
public class ActivityMyData extends BaseOtherActivity implements Observer {
    View v_statusbar;
    private ImageView close_icon;// 返回图片
    private TextView add_shap_title_tv;// 标题
    private RelativeLayout user_image_layout;// 头像布局
    private RelativeLayout user_name_layout;// 昵称布局
    private RelativeLayout user_sex_layout;// 性别布局
    private RelativeLayout user_phone_layout;// 绑定手机布局
    private RelativeLayout user_move_layout;// 房源管理布局
    private RelativeLayout user_identity_layout;// 身份验证布局
    private RelativeLayout  user_pass_layout;//修改密码
    private RoundImageView usericon_im;// 头像
    private TextView usericon_nicheng;// 昵称
    private TextView usericon_sex;// 性别
    private TextView usericon_phone;// 绑定手机
    private TextView usericon_move;// 房源管理
    private TextView usericon_identity;// 身份验证
    private String phonenumber;// 保存的手机号码

    CameraPopupWindow mCameraPopupWindow;

    public static String AVARTACTION = "com.zhujia.avart";

    private String localSelectPath;
    String sex;
    String type;
    UserPresenter userPresenter;
    protected String uid;
    private OnClickListener sexClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {
                case R.id.open_camera:
                    sex = "2";
                    type="男";
                    mCameraPopupWindow.dismiss();
                    break;
                case R.id.pick_image:
                    type="女";
                    sex = "1";
                    mCameraPopupWindow.dismiss();
                    break;
                case R.id.camera_cancel_tv:
                    type="保密";
                    sex = "0";
                    mCameraPopupWindow.dismiss();
                    break;
                default:
                    break;
            }
            uid = SPUtils
                    .get(ActivityMyData.this, null, SPContants.USER_ID, "")
                    + "";
            userPresenter.updateInfo(uid
                    , SPUtils.get(ActivityMyData.this, null, SPContants.RealName, "") + ""
                    ,SPUtils.get(ActivityMyData.this, null, SPContants.EMAIL, "") + ""
                    ,SPUtils.get(ActivityMyData.this, null, SPContants.Birthday, "") + ""
                    ,SPUtils.get(ActivityMyData.this, null, SPContants.NICK, "") + ""
            ,sex
            ,SPUtils.get(ActivityMyData.this, null, SPContants.QQ, "") + ""
            ,SPUtils.get(ActivityMyData.this, null, SPContants.SIGN, "") + "");
        }
    };

    /**
     * 显示数据
     */
    private void read() {
        // 昵称
        usericon_nicheng.setText((String) SPUtils.get(ActivityMyData.this,
                null, SPContants.NICK, ""));
        // 电话
        phonenumber = (String) SPUtils.get(ActivityMyData.this, null,
                SPContants.MOBILE, "");
        if (!phonenumber.equals("")) {
            try {
                String hintphone = phonenumber.substring(0, 3) + "****"
                        + phonenumber.substring(7, 11);
                usericon_phone.setText(hintphone);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        initavatar();
        // 性别
        String sex = (String) SPUtils.get(ActivityMyData.this, null,
                SPContants.SEX, "");
        if (!sex.equals("")) {
            try {
                if (sex.equals("0")) {
                    usericon_sex.setText("未知");
                } else if (sex.equals("1")) {
                    usericon_sex.setText("女");
                } else {
                    usericon_sex.setText("男");
                }
            } catch (Exception e) {
            }
        }

    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.close_icon:// 返回
                finish();
                break;
            case R.id.user_image_layout:// 头像布局
//                mCameraPopupWindow = new CameraPopupWindow(ActivityMyData.this,
//                        onclicklister);
//                mCameraPopupWindow.showAtLocation(v, Gravity.BOTTOM
//                        | Gravity.CENTER_HORIZONTAL, 0, 0);
                pic();
                break;
            case R.id.user_name_layout:// 昵称布局
                intent = new Intent(ActivityMyData.this, ActivityNiCheng.class);
                intent.putExtra("nick",usericon_nicheng.getText());
                startActivityForResult(intent, 1);
                break;
            case R.id.user_pass_layout:// 修改密码
                intent = new Intent(ActivityMyData.this, ActivityXiuGaiPass.class);
                startActivity(intent);
                break;
            case R.id.user_sex_layout:// 性别布局
                mCameraPopupWindow = new CameraPopupWindow(this, sexClickListener);
                mCameraPopupWindow.showAtLocation(v, Gravity.BOTTOM
                        | Gravity.CENTER_HORIZONTAL, 0, 0);
                ((TextView) mCameraPopupWindow.getContentView().findViewById(
                        R.id.open_camera)).setText("男");
                ((TextView) mCameraPopupWindow.getContentView().findViewById(
                        R.id.pick_image)).setText("女");
                ((TextView) mCameraPopupWindow.getContentView().findViewById(
                        R.id.camera_cancel_tv)).setText("保密");
                break;
            case R.id.user_phone_layout:// 绑定手机布局
                break;
            case R.id.user_identity_layout:// 身份验证布局
                if (usericon_identity.getText().equals("未认证")) {
                    intent = new Intent(ActivityMyData.this, ActivityRealName.class);
                    startActivity(intent);
                } else {
                    if (!usericon_identity.getText().equals(""))
                        ByAlert.alert(usericon_identity.getText().toString());
                }
                break;

            default:
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        uid = SPUtils.get(ActivityMyData.this, null, SPContants.USER_ID, "")+ "";
        showProgressDialog("正在获取信息",false);
        userPresenter.getPersonData(uid);
//        if (!(SPUtils.get(ActivityMyData.this, null,SPContants.IdentityValidate, "") + "").equals("1")){
//
//        }else {
//            usericon_identity.setText("已认证");
//        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();

    }
    //6.0添加拍照的权限
    private static String[] PERMISSIONS_CAMERA_AND_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA};
    public static boolean isCameraPermission(Activity context, int requestCode){
        if (Build.VERSION.SDK_INT >= 23) {
            int storagePermission = ActivityCompat.checkSelfPermission(context,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE);
            int cameraPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA);
            if (storagePermission != PackageManager.PERMISSION_GRANTED || cameraPermission!= PackageManager.PERMISSION_GRANTED ) {
                ActivityCompat.requestPermissions(context, PERMISSIONS_CAMERA_AND_STORAGE,
                        requestCode);
                return false;
            }
        }
        return true;
    }

    /**
     * 打开图库
     */
    private void pic() {
        isCameraPermission(this,1);
        ImageConfig imageConfig
                = new ImageConfig.Builder(new GlideLoader())
                .steepToolBarColor(getResources().getColor(R.color.blue))
                .titleBgColor(getResources().getColor(R.color.blue))
                .titleSubmitTextColor(getResources().getColor(R.color.white))
                .titleTextColor(getResources().getColor(R.color.white))
                // 开启单选   （默认为多选）
                .singleSelect()
                // 开启拍照功能 （默认关闭）
                .showCamera()
                // 已选择的图片路径
                // .pathList(path)
                // 拍照后存放的图片路径（默认 /temp/picture） （会自动创建）
                .filePath("/ImageSelector/Pictures")
                .build();
        ImageSelector.open(this, imageConfig);   // 开启图片选择器
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
//                usericon_nicheng.setText("" + data.getStringExtra("nickname"));
            }  else if (requestCode == ImageSelector.IMAGE_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
                List<String> pathList = data.getStringArrayListExtra(ImageSelectorActivity.EXTRA_RESULT);
                String paths="";
                for (String path : pathList) {
                    Log.i("ImagePathList", path);
                    paths=pathList.get(0);
                }
                onImage(paths);
            }
        }
    }

    /**
     * 上传图片
     * @param str 地址
     */
    private void onImage(String str){
        File files = new File(str);
        if (str == null) {
            ByAlert.alert("请上传相关图片");
            return;
        }
        Map<String, String> params = new HashMap<String, String>();
        params.put("uid",uid);
        params.put("type", "avatar");

        MultipartRequest multipartRequest = new MultipartRequest(
                NetPublicConstant.URL
                        + "/file/upload?client_id=by565fa4facdb191",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String arg0) {
                        Log.d("urlTime", arg0.toString());
                        allInfoFromJson(arg0.toString());
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError arg0) {
                // TODO Auto-generated method stub
                ByAlert.alert(arg0);
            }
        }, "image", files, params);
        MyApplcation.addRequest(multipartRequest);

    }
    public void allInfoFromJson(String jsonStr) {
        try {
            JSONArray jsonArray = new JSONObject(jsonStr).getJSONArray("data");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                String busName = jsonObject.getString("id");
                Log.d("busLin", busName);
                ByAlert.alert("上传成功");
                SPUtils.put(this, "", SPContants.AVATAR_URL, busName);
                initavatar();
                Intent intent = new Intent(AVARTACTION);
                sendBroadcast(intent);
                try {
                    closeProgressDialog();
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
            ByAlert.alert("上传失败");
        }

    }
    /**
     * 头像
     */
    private void initavatar() {
        String url = "" + SPUtils.get(this, null, SPContants.AVATAR_URL, "");
        System.out.println(url);
        if (!url.equals("")) {
            if (url.startsWith("http:")) {
                XImageLoader.load(url, usericon_im);
            } else if (url.equals("0")) {
                usericon_im.setImageResource(R.drawable.default_head);
            } else {
                XImageLoader.load(NetPublicConstant.IMAGE_URL + url,
                        usericon_im);
            }
        } else {
            usericon_im.setImageResource(R.drawable.default_head);
        }
    }

    @Override
    protected int layout_id() {
        // TODO Auto-generated method stub
        return R.layout.activity_gerendata;
    }

    @Override
    protected void onInitController() {
        // TODO Auto-generated method stub

    }

    @Override
    protected void onInit() {
        // TODO Auto-generated method stub

        setStatusBarHeight(v_statusbar);
        add_shap_title_tv.setText("个人信息");
        userPresenter = new UserPresenter(this);
        read();
    }

    @Override
    protected void onReadIntent(Bundle bundle) {
        // TODO Auto-generated method stub

    }

    @Override
    public void update(Observable observable, Object data) {
        // TODO Auto-generated method stub
        ResultEntity entity = handlerError(data);
        if (entity != null) {
            if (entity.getEventType() == UserPresenter.updateUser_success) {
                SPUtils.put(ActivityMyData.this,null,SPContants.SEX,sex);
                ByAlert.alert(entity.getData());
                userPresenter.getPersonData(uid);
            } else if (entity.getEventType() == UserPresenter.updateUser_fail) {
                ByAlert.alert(entity.getData());
            } else if (entity.getEventType() == UserPresenter.persondata_success) {
                PersonDataBean bean = (PersonDataBean) entity.getData();
                SavePersonData.saveData(ActivityMyData.this, bean);
                usericon_nicheng.setText(bean.getNickname());
                if (bean.getSex().trim().equals("0")){
                    usericon_sex.setText("保密");
                    type="保密";
                }else if (bean.getSex().trim().equals("1")){
                    usericon_sex.setText("女");
                    type="女";
                }else if (bean.getSex().trim().equals("2")){
                    usericon_sex.setText("男");
                    type="男";
                }
                if (bean.getIdentityValidate().trim().equals("2")) {
                    usericon_identity.setText("认证中");
                } else if (bean.getIdentityValidate().trim().equals("1")) {
                    usericon_identity.setText("已认证");
                } else {
                    usericon_identity.setText("未认证");
                }
            } else if (entity.getEventType() == UserPresenter.persondata_fail) {
                ByAlert.alert(entity.getData()+"");
            }
        }
        try {
            closeProgressDialog();
        } catch (Exception e) {
        }
    }

}
